package com.kevin.Code.Backtrack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author Vinlee Xiao
 * @Classname CombinationSumii
 * @Description Leetcode 40 组合总和 || 中等难度 回溯算法
 * @Date 2021/9/27 17:10
 * @Version 1.0
 */
public class CombinationSumii {

    List<List<Integer>> result = new ArrayList<>();
//    boolean[] visited;

    /**
     * @param candidates
     * @param target
     * @return
     */
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {

        List<Integer> combiner = new ArrayList<>();
        Arrays.sort(candidates);
        backtrack(candidates, combiner, target, 0, 0);

        return result;
    }


    /**
     * @param candidates
     * @param combiner
     * @param target
     * @param preSum
     * @param startIndex
     */
    public void backtrack(int[] candidates, List<Integer> combiner, int target, int preSum, int startIndex) {


        if (preSum == target) {
            result.add(new ArrayList<>(combiner));
            return;
        }

        for (int i = startIndex; i < candidates.length; i++) {
            if (preSum < target) {

                if (i > startIndex && candidates[i] == candidates[i - 1]) {

                    continue;
                }

                combiner.add(candidates[i]);
                backtrack(candidates, combiner, target, preSum + candidates[i], i + 1);
                combiner.remove(combiner.size() - 1);

            } else {
                break;
            }

        }
    }


    public static void main(String[] args) {

        int[] candidates = new int[]{10, 1, 2, 7, 6, 1, 5};
        CombinationSumii c1 = new CombinationSumii();
        List<List<Integer>> lists = c1.combinationSum2(candidates, 8);

        for (List<Integer> list : lists) {
            for (Integer num : list) {
                System.out.print(num + " ");
            }
            System.out.println();
        }
    }
}
